//
//  TeacherApp.swift
//  Teacher
//
//  Created by qh w on 2021/5/3.
//

import SwiftUI
import WidgetKit
import BackgroundTasks
import ActivityKit

@main
struct TeacherApp: App {
    @State var isNotFirstLaunch = UserDefaults.standard.bool(forKey: "isNotFirstLaunch")
    @State var isVerified = false
    @State var requests: [UNNotificationRequest] = []
    @Environment(\.scenePhase) var scenePhase
    
    //    init() {
    //        let id =  "com.classmanager.teacher.liveactivity"
    //        BGTaskScheduler.shared.register(forTaskWithIdentifier: id, using: nil) { task in
    //            task.expirationHandler = {
    //                print("BTTask failed!")
    //                task.setTaskCompleted(success: false)
    //            }
    //
    //            //MARK: Do BGTask
    //            print("Doing BGTask...")
    //            let initialContentState = HomeScreenWidgetsAttributes.ContentState(remainingMinute: 5)
    //            let activityAttributes = HomeScreenWidgetsAttributes(totalMinute: 10, classTypeString: "语文", classString: "高一3")
    //            do {
    //                if #available(iOS 16.1, *) {
    //                    _ = try Activity.request(attributes: activityAttributes, contentState: initialContentState)
    //                } else {
    //                    // Fallback on earlier versions
    //                }
    //                print("Requested a Live Activity.")
    //            } catch (let error) {
    //                print("Error requesting a Live Activity \(error.localizedDescription).")
    //            }
    //
    //            //MARK: Request a new task
    //            let request = BGAppRefreshTaskRequest(identifier: id)
    //
    //            request.earliestBeginDate = Date(timeIntervalSinceNow: 10)
    //            try? BGTaskScheduler.shared.submit(request)
    //
    //            print("BGTask succeeded!")
    //            task.setTaskCompleted(success: true)
    //        }
    //    }
    
    var body: some Scene {
        WindowGroup {
            if isNotFirstLaunch {
                LoadingView(content: {ContentView(UserData: CoreData(classNameStr: ""), showWarning: .constant(false))})
            }
            else {
                WelcomeView(requestCamera: true, content: {ContentView(UserData: CoreData(classNameStr: ""), showWarning: .constant(false))}).environmentObject(CoreData(classNameStr: ""))
            }
        }.onChange(of: scenePhase) { scene in
            if scene == .background {
                //                exit(0)
                //MARK: Refresh Widget Data
                WidgetCenter.shared.reloadAllTimelines()
                
                
                
                //                //MARK: Submit BGTask
                //                let id = "com.classmanager.teacher.liveactivity"
                //                let request = BGProcessingTaskRequest(identifier: id)
                //                request.earliestBeginDate = Date(timeIntervalSinceNow: 5)
                //                do  {
                //                    try BGTaskScheduler.shared.submit(request)
                //                }
                //                catch let error as NSError {
                //                    print(error)
                //                }
                
                //MARK: Load Notifications
                let center = UNUserNotificationCenter.current()
                for request in requests {
                    center.add(request) { error in
                        if let error = error {
                            print(error)
                        }
                    }
                }
                print(requests)
                center.getPendingNotificationRequests(completionHandler: {
                    print($0)
                })
            }
            if scene == .active && !UserDefaults.standard.bool(forKey: "2023Beta3Fix") && UserDefaults.standard.bool(forKey: "isNotFirstLaunch") && UserDefaults(suiteName: "group.classmanager")!.string(forKey: "server") != nil {
                Patch2023Beta3Fix()
                UserDefaults.standard.set(true, forKey: "2023Beta3Fix")
            }
            if scene == .active {
                let center = UNUserNotificationCenter.current()
                center.requestAuthorization(options: [.alert, .badge, .sound]) { (_, _) in }
            }
            
            if scene == .active {
                let center = UNUserNotificationCenter.current()
                var oldRequests: [UNNotificationRequest] = []
                center.getPendingNotificationRequests(completionHandler: {
                    oldRequests = $0
                })
                requests = []
                let classData = ClassNameData()
                classData.IS_INTERNET_OPERATION_ALLOWED_FLAG = true
                _ = classData.downloadDataByHttp {
                    for _class in classData.ClassName {
                        let classroom = CoreData(classNameStr: _class.name)
                        classroom.IS_INTERNET_OPERATION_ALLOWED_FLAG = true
                        _ = classroom.downloadDataByHttp {
                            for _event in classroom.events {
                                if _event.techer == UserDefaults(suiteName: "group.classmanager")!.string(forKey: "teacherName") && _event.state == -1 && Date().timeIntervalSince1970<=_event.start
                                {
                                    let content = UNMutableNotificationContent()
                                    content.title = classroom.classes[_event._class].name
                                    content.body = "\(_event.techer)快到\(_class.name)上课！"
                                    content.sound = .default
                                    if #available(iOS 15.0, *) {
                                        content.interruptionLevel = .timeSensitive
                                    } else {
                                        // Fallback on earlier versions
                                    }
                                    var isRequested = false
                                    for request in oldRequests {
                                        if content == request.content {
                                            isRequested = true
                                            break
                                        }
                                    }
                                    if isRequested {
                                        continue
                                    }
                                    let date = Calendar.current.dateComponents([.year, .month, .day], from: Date(timeIntervalSince1970: _event.start))
                                    print(date)
                                    //                                    let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: false)
                                    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: _event.start-Date().timeIntervalSince1970, repeats: false)
                                    let request = UNNotificationRequest(identifier: "ClassBegin\(_event.start)", content: content, trigger: trigger)
                                    requests.append(request)
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
